#!/bin/bash

function delete_lced_msg_queues {

# Make sure that the LCE deleted its msg_queues.  Delete them
# here if they still exist

    # Read the file that has the process IDs in it.
    # look for msg_queues that have this process ID (ipcs -p)
    # and then remove them

    if [ -a /var/hsc/lced_proc_ids ]
    then
        for i in `cat /var/hsc/lced_proc_ids`
        do
          REMOVE_MSGQ=`ipcs -p | grep $i | awk {'print $1'}`

          # this variable will have multiple process ids in it
          # so we need to handle one proc id at a time
          for j in $REMOVE_MSGQ
           do
           if [ "$j" != "" ]
            then
              ipcrm msg $j
            fi
           done

        done

        rm /var/hsc/lced_proc_ids
    fi
}

# Clean up message queue
#
delete_lced_msg_queues

# Start the lced
#
ulimit -c 1000000

# For debug; abort() is called immediately if there's detected
# heap corruption
# sashok -> only valid for malloc(), free(), and realloc() ?
export MALLOC_CHECK_=2

if [ -f /var/hsc/log/.DEBUG_HSC ]; then
   /opt/hsc/bin/lced 0x05 > /var/hsc/log/lced.log 2>&1 &
   TOP_LCED_ID=$!
else
   /opt/hsc/bin/lced 0x05 &
   TOP_LCED_ID=$!
fi

# Record the thread ids for the started LCED.
# ! For the new version of LCED (soc_server.c v1.21), the lced_proc_ids
#   may be empty because the LCED maybe in 'waiting timeout' state.
# 
sleep 5
ps -efwww | grep lced | awk {'print $2'} > /var/hsc/lced_proc_ids

wait $TOP_LCED_ID
echo "LCED stopped on "`date` > /tmp/lcedStopped.log

